package com.comcast.util;

import java.net.URL;
import java.util.Properties;

/*import java.util.Hashtable;
import java.util.StringTokenizer;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.config.PropertySetter;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggerRepository;*/

import org.apache.log4j.helpers.FileWatchdog;
import org.apache.log4j.LogManager;

public class PropertyConfigurator extends org.apache.log4j.PropertyConfigurator {
	//static final String AUDITLOGGER_PREFIX = "log4j.auditlogger.methods.";
	//static final String AUDITLOGGER_METHODS_PROP = "log4j.auditlogger.methods";

	public static void configure(String configFilename) {
		new PropertyConfigurator().doConfigure(configFilename, LogManager
				.getLoggerRepository());
	}

	public static void configure(URL configURL) {
		new PropertyConfigurator().doConfigure(configURL, LogManager
				.getLoggerRepository());
	}

	public static void configure(Properties properties) {
		new PropertyConfigurator().doConfigure(properties, LogManager
				.getLoggerRepository());
	}

	public static void configureAndWatch(String configFilename) {
		configureAndWatch(configFilename, 60000L);
	}

	public static void configureAndWatch(String configFilename, long delay) {
		PropertyWatchdog pdog = new PropertyWatchdog(configFilename);
		pdog.setDelay(delay);
		pdog.start();
	}

	/*@Override
	public void doConfigure(Properties properties, LoggerRepository hierarchy) {
		super.doConfigure(properties, hierarchy);
		String methods = properties.getProperty(AUDITLOGGER_METHODS_PROP);
		Hashtable<String, MethodConfiguration> methodConfigurations = new Hashtable<String, MethodConfiguration>();
		if (!StringUtils.isEmpty(methods)) {
			LogLog.debug("Parsing properties for methods [" + methods + "]");
			StringTokenizer st = new StringTokenizer(methods, ",");

			while (st.hasMoreTokens()) {
				String methodName = st.nextToken().trim();
				LogLog.debug("Getting props for method name = " + methodName);
				if (methodConfigurations.get(methodName) != null)
					continue;

				MethodConfiguration methodConfig = new MethodConfiguration();
				methodConfig.setName(methodName);
				PropertySetter.setProperties(methodConfig, properties, AUDITLOGGER_PREFIX + methodName + ".");
				methodConfigurations.put(methodConfig.getName(), methodConfig);
			}
		}
		AuditLoggerConfiguration.getInstance().setMethodConfigurations(methodConfigurations);
	}*/

	static class PropertyWatchdog extends FileWatchdog {
		PropertyWatchdog(String filename) {
			super(filename);
		}

		public void doOnChange() {
			new PropertyConfigurator().doConfigure(this.filename, LogManager.getLoggerRepository());
		}
	}
}
